<template>
    <div id="params">
       <separator :nameList='nameList'></separator>
       <el-card>
          <el-alert show-icon title="注意：只允许为第三级设置相关参数" :closable="false" type="warning"></el-alert>
          <el-row class="box-row">
            <el-col>
              <span class="changeGoodsList">选择商品分类</span>
              <el-cascader v-model="paramsValue" :options="paramsOptions" expandTrigger="hover" :props="paramsProps" @change="ParamsHandleChange"></el-cascader>
            </el-col>
          </el-row>
          <!-- 选项卡 -->
          <el-tabs v-model="activeName" @tab-click="activeHandleClick">
            <!-- 动态参数 -->
            <el-tab-pane label="动态参数" name="many">
                <el-button type="primary" :disabled="showBtn"  @click="addParamsDialog=true">添加参数</el-button>
                  <el-table :data="dynamicData" style="width: 60%;margin-bottom: 20px;"  border>
                     <el-table-column type="expand" >
                        <template slot-scope="scope">
                            <el-tag v-for="(item,index) in scope.row.attr_vals" :key='index+"22"'  closable @close='closeTag(index,scope.row)' type='success' >{{item}}</el-tag>
                            <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" 
                                      @keyup.enter.native="manyInputConfirm(scope.row)" @blur="manyInputConfirm(scope.row)">
                            </el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                        </template>
                     </el-table-column>
                    <el-table-column type="index" ></el-table-column>
                    <el-table-column prop="attr_name" label="参数名称" ></el-table-column>
                    <el-table-column label="操作" width="200px" >
                       <template slot-scope="scope">
                         <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditorBtn(scope.row)">编辑</el-button>
                         <el-button type="danger" icon="el-icon-delete" size="mini" @click="delParamsList(scope.row)">删除</el-button>
                       </template>
                    </el-table-column>
                  </el-table>
            </el-tab-pane>
            <!-- 静态属性 -->
            <el-tab-pane label="静态属性" name="only">
                <el-button type="primary" :disabled="showBtn" @click="addParamsDialog=true">添加属性</el-button>
                <el-table :data="staticData" style="width: 60%;margin-bottom: 20px;" border>
                     <el-table-column type="expand" >
                        <template slot-scope="scope">
                            <el-tag v-for="(item,index) in scope.row.attr_vals" :key='index+"22"'  closable @close='closeTag(index,scope.row)' type='success' >{{item}}</el-tag>
                            <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" 
                                      @keyup.enter.native="manyInputConfirm(scope.row)" @blur="manyInputConfirm(scope.row)">
                            </el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                        </template>
                     </el-table-column>
                    <el-table-column type="index" ></el-table-column>
                    <el-table-column prop="attr_name" label="属性名称" ></el-table-column>
                    <el-table-column label="操作" width="200px" >
                       <template slot-scope="scope">
                         <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditorBtn(scope.row)">编辑</el-button>
                         <el-button type="danger" icon="el-icon-delete" size="mini" @click="delParamsList(scope.row)">删除</el-button>
                       </template>
                    </el-table-column>
                  </el-table>
            </el-tab-pane>
          </el-tabs>
       </el-card>
       <!-- 添加属性和参数对话框按钮 -->
       <el-dialog :title="addParamsTitle" ref="addParamsRef" :visible.sync="addParamsDialog"  width="40%" @close='addParamsClose'>
          <el-form ref="paramsFormRef" :model="addParamsForm" :rules='addFormRules' label-width="80px">
            <el-form-item :label="showAddLabel" prop="attr_name">
              <el-input v-model="addParamsForm.attr_name"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addParamsDialog = false">取 消</el-button>
            <el-button type="primary" @click="addParamsSure">确 定</el-button>
          </span>
       </el-dialog>

       <!-- 修改属性和参数对话框按钮 -->
       <el-dialog :title="addParamsTitle" ref="editorParamsRef" :visible.sync="showEditorParams"  width="40%">
          <el-form ref="editorParamsRef" :model="addParamsForm" :rules='addFormRules' label-width="80px">
            <el-form-item :label="showAddLabel" prop="attr_name">
              <el-input v-model="addParamsForm.attr_name"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="showEditorParams = false">取 消</el-button>
            <el-button type="primary" @click="showEditorSure">确 定</el-button>
          </span>
       </el-dialog>
    </div>
</template>

<script>
  import Separator from 'components/content/separator/Separator'
  import { getGoodsPrd} from 'network/goods/categories'
  import {getParams ,setParamsList,getParamsIdList,setParamsName,delParams} from 'network/goods/params'
  export default {
    name:'Params',
    components:{
      Separator
    },
    data(){
      return{
        nameList:['商品管理','分类参数'],
        paramsProps:{
          value:'cat_id',
          label:'cat_name',
          children:'children'
        }, 
        //获取的数据
        paramsOptions:[],
        //级联选择器所选值
        paramsValue:[],
        // 被激活的标签名称
        activeName: 'many',
        //保存静态的数据
        staticData:[],
        //保存动态数据
        dynamicData:[],
        //添加按钮会话框
        addParamsDialog:false,
        addTitle:'',
        addParamsForm:{
          attr_name:''
        },
        addLabel:'',
        addFormRules:{
          attr_name:[
            {required:true,message:"'请输入'+ showAddLabel",trigger:'blur'},
            {min:2,max:10,trigger:'blur'}
          ]
        },
        //编辑会话框
        showEditorParams:false,
        //保存点击编辑时 用到的属性id值
        editorId:'',
      }
    },
    created(){
      this.getChenge()
    },
    methods: {
      //选择商品分类 数据获取
      getChenge(){
        getGoodsPrd(3).then(res=>{
          if(!res.data.meta.status===200){
            return this.$message.error('获取父级列表数据失败');
          }
          this.paramsOptions = res.data.data;             
          },err=>{
            console.log(err)
          })    
      },
      //根据分类的id 查找出对应的数据
      getParamsList(id,sel){
        getParams(id,sel).then(res=>{
            console.log(res);
            if(!res.data.meta.status===200){
              return this.$message.error('获取数据失败');
            }
            res.data.data.forEach(element => {
            element.attr_vals = element.attr_vals ? element.attr_vals.split(',') :[];
            //控制文本框的显示与隐藏
            element.inputVisible=false;
            //文本框中输入的值
            element.inputValue='';
            });
            if(sel==='only'){
              this.staticData=res.data.data
            }else{
              this.dynamicData=res.data.data
            }
          },err=>{
            console.log(err);
          })   
          console.log(this.staticData);
           console.log(this.dynamicData);
      }, 
      // 联动数据发生改变时发生触发
      ParamsHandleChange(){
        if(this.paramsValue.length!==3){
           this.dynamicData=[];
           this.staticData=[];
          return this.$message.error('只允许修改三级分类');
        }
        console.log(this.paramsValue.length)
        this.getParamsList(this.paramsValue[2],this.activeName);
       


      },
      // tab 被选中时触发
      activeHandleClick() {
        if(this.paramsValue.length!==3){
          return this.$message.error('只允许修改三级分类');
        }
        this.getParamsList(this.paramsValue[2],this.activeName)
      },
      //关闭添加对话框
      addParamsClose(){
        this.$refs.paramsFormRef.resetFields()
      } ,
      //点击确定添加按钮
      addParamsSure(){
        this.$refs.editorParamsRef.validate(val =>{
          if(!val){
            return false
          }
        });
        setParamsList(this.paramsValue[2],this.addParamsForm.attr_name,this.activeName).then(res=>{
            if(!res.data.meta.status===201){
              return this.$message.error('获取数据失败');
            }
            this.$message.success('添加成功');
            this.getParamsList(this.paramsValue[2],this.activeName);
            this.addParamsDialog=false;
        },err=>{
           console.log(err);
        })
      },
      //点击编辑会话框
     showEditorBtn(config){
       this.showEditorParams=true;
       this.editorId=config.attr_id;
       getParamsIdList(this.paramsValue[2],config.attr_id,this.activeName).then(res=>{
         if(!res.data.meta.status===200){
             this.showEditorParams=false;
             return this.$message.error('获取数据失败');
          }
          this.addParamsForm.attr_name=res.data.data.attr_name;
          console.log(this.addParamsForm.attr_name);
       },err=>{
          console.log(err)
       })
     },
     //编辑按钮确定提交数据
     showEditorSure(){
       setParamsName(this.paramsValue[2],this.editorId, this.addParamsForm.attr_name,this.activeName).then(res=>{
           if(!res.data.meta.status===200){
             return this.$message.error('修改数据失败');
          }
          this.$message.success('修改数据成功');
          this.getParamsList(this.paramsValue[2],this.activeName);
          this.showEditorParams=false;
       },err=>{
          console.log(err);
       })
     } ,
     //删除按钮
     delParamsList(config){
        this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delParams(this.paramsValue[2],config.attr_id).then(res=>{
           if(!res.data.meta.status===200){
             this.showEditorParams=false;
             return this.$message.error('删除数据失败');
          }
          this.getParamsList(this.paramsValue[2],this.activeName);
          this.showEditorParams=false;
        },err=>{
            console.log(err);
        })
          this.$message({ type: 'success', message: '删除成功!' });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
      //关闭tab 标签时触发
      closeTag(index,row){
        row.attr_vals.splice(index,1); 
        console.log(row.attr_vals);
        setParamsName(this.paramsValue[2],row.attr_id,row.attr_name,this.activeName,row.attr_vals).then(res=>{
           if(!res.data.meta.status===200){
             return this.$message.error('操作失败');
          }
          this.$message.success('操作成功');
       },err=>{
          console.log(err)
       })
      },
     //动态参数里 input 失去焦点和键盘回车时触发
      manyInputConfirm(type){  
       if(type.inputValue.trim().length===0){
          type.inputValue='';
          type.inputVisible=false
          return false
       }
      //  如果没有return 则需要做后续处理
       type.attr_vals.push(type.inputValue);
       type.inputVisible=false
      var attr_vals= type.attr_vals.join(',')
       setParamsName(this.paramsValue[2],type.attr_id,type.attr_name,this.activeName,attr_vals).then(res=>{
           if(!res.data.meta.status===200){
             return this.$message.error('操作失败');
          }
          this.$message.success('操作成功');
       },err=>{
          console.log(err)
       })
     },
     //点击添加tag按钮
     showInput(type){
       //文本框自动获取焦点  
       type.inputVisible = true;
       //$nextTick函数的作用 就是当页面上的元素被重新渲染之后 才会回调函数中的代码
       this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
       });
     }    
    },
    computed:{
      showBtn(){
         return this.paramsValue.length !== 3
      },
     
      addParamsTitle(){
       if(this.activeName==='many'){
         return this.addTitle='添加动态参数'
       }else {
         return this.addTitle='添加静态属性'
       }
     },
      showAddLabel(){
       if(this.activeName==='many'){
         return this.addLabel='动态参数'
       }else {
         return this.addLabel='静态属性'
       }  
     }
    }
  }
</script>

<style lang="less" scoped>
  .box-row{
    margin-top: 20px;
  }
  .changeGoodsList{
    margin-right: 10px;
  }
  .el-cascader{
    width: 350px;
  }
  .el-tabs{
    margin-top: 15px;
  }
  .el-table{
    margin-top: 15px;
  }
  .el-tag{
    margin: 10px;
  }
  .input-new-tag{
    width: 100px;
  }
</style>
